import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:talk/api/AlarmApi.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/CustomSwitch.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/Device.dart';
import 'model/DeviceAlarm.dart';

class DeviceLockPage extends StatefulWidget {
  const DeviceLockPage({
    super.key,
    this.deviceId,
    this.device,
  });

  final int? deviceId;
  final Device? device;

  @override
  State<DeviceLockPage> createState() => _DeviceLockPageState();
}

class _DeviceLockPageState extends State<DeviceLockPage> {
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();
  late int _deviceId;
  Device? _device;
  List<DeviceAlarm> _deviceAlarms = []; // 存储设备报警数据
  bool _isLoading = true; // 加载状态
  late int interCom; // 对讲状态变量
  //app报警
  late int interAppAlarm;

  @override
  void initState() {
    super.initState();

    _deviceId = widget.deviceId!;
    _device = widget.device!;

    interCom = _device?.timeWatermark ?? 0; // 初始化时同步timeWatermark的值
    interAppAlarm = _device?.appMessage ?? 0; // 初始化时同步timeWatermark的值
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      final response = await _deviceApi.getDeviceAlarm(_deviceId);
      if (response.code == 200) {
        // 解析数据
        setState(() {
          _deviceAlarms = (response.rows as List<dynamic>)
              .map((item) => DeviceAlarm.fromJson(item))
              .toList();
          _isLoading = false;
        });
      } else {
        Toast.show("获取数据失败，错误码: ${response.code}");
        setState(() => _isLoading = false);
      }
    } catch (e) {
      // Toast.show("网络请求错误: $e");
      Toast.show("网络请求错误");
      setState(() => _isLoading = false);
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('lg_zhiliansuoshezhi'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Container(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            const SizedBox(height: 20),

            // 构建摄像头列表
            ..._deviceAlarms.map((alarm) {
              return Column(
                // padding: const EdgeInsets.symmetric(vertical: 0.0),
                children: [
                    ItemView(
                      width: double.infinity,
                      height: 50,
                      leftPadding: 10,
                      rightPadding: 20,
                      leftWidget: Row(
                        children: [
                          const SizedBox(width: 10),
                          Text(
                            alarm.camName ?? AppLocale.text('d_weizhi'),
                            style: const TextStyle(
                              fontSize: 15.0,
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                      rightWidget: Row(
                        children: [
                          // const SizedBox(width: 8),
                          Image.asset("images/images/deviceSetting/a1.png", width: 25),
                        ],
                      ),
                      borderRadius: 8,
                      onTap: () {
                        BrnMiddleInputDialog(
                            title: AppLocale.text('d_xiugaibaojingming'),
                            // hintText: alarm.camName,
                            // 通过inputEditingController设置默认值
                            inputEditingController: TextEditingController(text: alarm.camName),
                            cancelText: AppLocale.text('cancel'),
                            confirmText: AppLocale.text('confirm'),
                            autoFocus: true,
                            maxLength: 1000,
                            maxLines: 2,
                            // inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                            dismissOnActionsTap: false,
                            barrierDismissible: true,
                            onConfirm: (value) async {
                              final toUpdate = {
                                "camId": alarm.camId,
                                "camName": value,
                                "doorLockDelay": null,
                              };
                              //更新数据
                              final response = await _alarmApi.directLock(toUpdate);
                              if (response.code == 200) {
                                setState(() {
                                  alarm.camName = value;
                                });
                              }else {
                                Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
                              }

                              Navigator.pop(context);
                            },
                            onCancel: () {
                              Navigator.pop(context);
                            }).show(context);
                      },
                  ),


                  ItemView(
                    width: double.infinity,
                    height: 50,
                    leftPadding: 10,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        const SizedBox(width: 10),
                        Text(
                          AppLocale.text('d_menkousuokaimenyanshi'),
                          style: const TextStyle(
                            fontSize: 15.0,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                    rightWidget: Row(
                      children: [
                        Row(
                          children: [
                            Text(
                              alarm.doorLockDelay == 0 ? '0s'
                              : alarm.doorLockDelay == 1 ? '1s'
                              : alarm.doorLockDelay == 2 ? '2s'
                              : alarm.doorLockDelay == 3 ? '3s'
                              : alarm.doorLockDelay == 4 ? '4s'
                              : alarm.doorLockDelay == 5 ? '5s'
                              : alarm.doorLockDelay == 6 ? '6s'
                              : alarm.doorLockDelay == 7 ? '7s'
                              : alarm.doorLockDelay == 8 ? '8s'
                              : alarm.doorLockDelay == 9 ? '9s'

                                  : AppLocale.text('d_qitaduijaing'),
                              style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.black54
                              ),
                            ),
                            const SizedBox(width: 5,),
                            const Icon(
                              Icons.arrow_forward_ios,
                              color: Colors.grey,
                              size: 14,
                            ),
                            const SizedBox(width: 5),
                          ],
                        )
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {

                      dynamic ioSelect = alarm.doorLockDelay;

                      // 选项列表（label 是显示文案，value 是实际值）
                      List<Map<String, dynamic>> ioList = [
                        {'label': '0s', 'value': 0},
                        {'label': '1s', 'value': 1},
                        {'label': '2s', 'value': 2},
                        {'label': '3s', 'value': 3},
                        {'label': '4s', 'value': 4},
                        {'label': '5s', 'value': 5},
                        {'label': '6s', 'value': 6},
                        {'label': '7s', 'value': 7},
                        {'label': '8s', 'value': 8},
                        {'label': '9s', 'value': 9},
                      ];

                      showModalBottomSheet(
                        context: context,
                        backgroundColor: Colors.transparent,
                        builder: (BuildContext dialogContext) {
                          return CustomBottomPicker(
                            title: AppLocale.text('d_menkousuokaimenyanshi'),
                            height: 300,
                            list: ioList,
                            selectedColor: Colors.blue,
                            backgroundColor: Colors.white,
                            initialValue: ioSelect,
                            //圆圈样式
                            selectedShapeType: SelectedShapeType.hollowCircle,
                            onSelect: (newValue) async {


                              final toUpdate = {
                                "camId": alarm.camId,
                                "camName": null,
                                "doorLockDelay": newValue,
                              };
                              //更新数据
                              final response = await _alarmApi.directLock(toUpdate);
                              if (response.code == 200) {
                                // 选中值变化时的回调，可在此更新页面状态
                                setState(() {
                                  // 示例：如果需要把 newValue 存到 _device 或其他变量，可自行处理
                                  // _device.someProperty = newValue;
                                  alarm.doorLockDelay = newValue;
                                });
                              }else {
                                Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
                              }
                              // Navigator.pop(context);
                            },
                          );
                        },
                      );

                    },
                  ),


                  const SizedBox(height: 20,),


                ]
              );
            }).toList(),

            const SizedBox(height: 10),


            ItemView(
              width: double.infinity,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_shineijisuoyanshi'),
                    style: TextStyle(
                      fontSize: 15.0,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                dynamic ioSelect = _device?.indoorLockDelay;

                // 选项列表（label 是显示文案，value 是实际值）
                List<Map<String, dynamic>> ioList = [
                  {'label': '0s', 'value': 0},
                  {'label': '1s', 'value': 1},
                  {'label': '2s', 'value': 2},
                  {'label': '3s', 'value': 3},
                  {'label': '4s', 'value': 4},
                  {'label': '5s', 'value': 5},
                  {'label': '6s', 'value': 6},
                  {'label': '7s', 'value': 7},
                  {'label': '8s', 'value': 8},
                  {'label': '9s', 'value': 9},
                ];

                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.transparent,
                  builder: (BuildContext dialogContext) {
                    return CustomBottomPicker(
                      title: AppLocale.text('d_shineijisuoyanshi'),
                      height: 300,
                      list: ioList,
                      selectedColor: Colors.blue,
                      backgroundColor: Colors.white,
                      initialValue: ioSelect,
                      //圆圈样式
                      selectedShapeType: SelectedShapeType.hollowCircle,
                      onSelect: (newValue) async {

                        final toUpdate = {
                          "deviceId": _device?.deviceId,
                          "indoorLockDelay": newValue,
                        };
                        //更新数据
                        final response = await _deviceApi.indoorLockDelay(toUpdate);
                        if (response.code == 200) {
                          // 选中值变化时的回调，可在此更新页面状态
                          setState(() {
                            // 示例：如果需要把 newValue 存到 _device 或其他变量，可自行处理
                            // _device.someProperty = newValue;
                            ioSelect = newValue; // 这里只更新了局部变量
                            _device?.indoorLockDelay = newValue;
                          });
                        }else {
                          Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
                        }
                        // Navigator.pop(context);
                      },
                    );
                  },
                );



              },
            ),







          ],
        ),
      ),
    );
  }
}






























